import React, { Component } from 'react';
import {
  Form,
  Input,
  Table,
  Button,
  Radio,
  Divider,
  Popconfirm,
  Row,
  Col,
  Alert,
  DatePicker,
  Select,
  Modal,
} from 'antd';
import { connect } from 'dva';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { soldSearch } from '@/services/user';
import moment from 'moment';
import Add from './add';
import Edit from './edit';
import Details from './Details';
import styles from './styles.less';

const { Option } = Select;
const { MonthPicker, RangePicker } = DatePicker;
class Order extends Component<any, any> {
  state = {
    soldAdd: false,
    visible: false,
    buyEdit: false,
    soldEdit: false,
    selectDate: 'day',
    page: 1,
    size: 10,
    startTime: 0,
    endTime: Date.now(),
    personData: [],
  };
  componentDidMount() {
    // this.handleSearch();
    this.props.dispatch({
      type: 'order/reFresh',
      payload: true,
    });
  }
  componentDidUpdate() {
    const { isRefresh } = this.props;
    if (isRefresh) {
      setTimeout(() => {
        this.handleSearch();
      }, 200);
    }
  }
  handlSelect = (e: any) => {
    this.setState({ selectDate: e.target.value });
  };
  handleSearch = () => {
    const data = this.props.form.getFieldsValue();
    const { startTime, endTime, page, size } = this.state;
    const { orderType } = this.props;
    this.props.dispatch({
      type: 'order/list',
      payload: {
        ...data,
        type: data.type == '2' ? null : data.type,
        startDate: startTime,
        endDate: endTime,
        page,
        size,
      },
      orderType: orderType,
    });
  };
  handleDown = () => {
    const data = this.props.form.getFieldsValue();
    const { startTime, endTime, page, size } = this.state;
    const { orderType } = this.props;
    let orderStatus = 1;
    let orderText = '未结算订单';
    switch (orderType) {
      case 'pendingOrder':
        orderText = '未结算订单';
        orderStatus = 1;
        break;
      case 'settledOrder':
        orderText = '结算订单';
        orderStatus = 2;
        break;
      default:
        orderText = '无效订单';
        orderStatus = 3;
        break;
    }
    this.props.dispatch({
      type: 'order/down',
      payload: {
        ...data,
        orderDownloadType: orderStatus,
        type: data.type == '2' ? null : data.type,
        startDate: startTime,
        endDate: endTime,
        page,
        size,
      },
      filename: orderText,
    });
  };
  handleSettlement = (id: any) => {
    this.props.dispatch({
      type: 'order/settlement',
      payload: {
        ids: id,
      },
      orderType: 'settledOrder',
    });
  };
  handleReset = () => {
    this.props.form.resetFields();
    console.log(this.props.form.getFieldsValue());
  };
  render() {
    const { orderType, isRefresh } = this.props;
    const { selectDate, page, size, visible, buyEdit, soldEdit, personData, soldAdd } = this.state;
    const { getFieldDecorator } = this.props.form;
    const { dataSource, currentpage, total } = this.props;
    const columns = [
      {
        title: '序号',
        align: 'center',
        fixed: 'left',
        width: 50,
        render: (text: any, record: any, index: any) => `${index + 1}`,
      },
      {
        title: '订单创建人',
        dataIndex: 'creatorName',
        fixed: 'left',
        width: 100,
        align: 'center',
      },
      {
        title: '订单号',
        dataIndex: 'id',
        width: 100,
        align: 'center',
      },
      {
        title: '方式',
        dataIndex: 'typeName',
        width: 100,
        align: 'center',
      },
      {
        title: '人员',
        dataIndex: 'staffName',
        width: 100,
        align: 'center',
      },
      {
        title: '酒类',
        dataIndex: 'wineName',
        width: 100,
        align: 'center',
      },
      {
        title: '仓库',
        dataIndex: 'wareHouseName',
        width: 100,
        align: 'center',
      },

      {
        title: '公司核定买入价',
        dataIndex: 'companyPrice',
        width: 100,
        align: 'center',
      },
      {
        title: '员工买入单价',
        dataIndex: 'staffPrice',
        width: 100,
        align: 'center',
      },
      {
        title: '数量',
        dataIndex: 'quantity',
        width: 100,
        align: 'center',
      },
      {
        title: '单位',
        dataIndex: 'quantityComments',
        width: 100,
        align: 'center',
      },
      {
        title: '运费',
        dataIndex: 'freight',
        width: 100,
        align: 'center',
      },
      {
        title: '其它费用',
        dataIndex: 'otherFee',
        width: 100,
        align: 'center',
      },
      {
        title: '其它费用备注',
        dataIndex: 'otherFeeComments',
        width: 100,
        align: 'center',
      },
      {
        title: '成交时间',
        dataIndex: 'dealTime',
        width: 100,
        align: 'center',
        render: (text: any) => {
          return (
            <>
              <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
            </>
          );
        },
      },
      {
        title: '订单状态',
        dataIndex: 'orderStatus',
        width: 100,
        align: 'center',
      },

      {
        title: '操作',
        dataIndex: 'operate',
        width: 140,
        align: 'center',
        fixed: 'right',
        render: (text: any, record: any) => {
          return (
            <>
              {orderType == 'pendingOrder' ? (
                <>
                  <Popconfirm
                    title="此订单将流向结算订单目录里面"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => {
                      this.handleSettlement(record.id);
                    }}
                  >
                    <span>
                      <a>结算</a>
                    </span>
                  </Popconfirm>
                  <Divider type="vertical" />
                </>
              ) : null}

              {orderType == 'settledOrder' ? (
                <>
                  <Popconfirm
                    title="此订单将生成公司及员工利润"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => {
                      this.props.dispatch({
                        type: 'order/profit',
                        payload: {
                          ids: record.id,
                        },
                      });
                    }}
                  >
                    <span>
                      <a>转化利润</a>
                    </span>
                  </Popconfirm>
                  <Divider type="vertical" />
                </>
              ) : null}
              {orderType != 'invalidOrder' ? (
                <>
                  <Popconfirm
                    title="此订单将放入无效订单，且此单不会记录到利润中"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => {
                      const { dispatch } = this.props;
                      if (dispatch) {
                        dispatch({
                          type: 'order/delete',
                          payload: {
                            ids: record.id,
                          },
                          orderType: 'invalidOrder',
                        });
                      }
                    }}
                  >
                    <span>
                      <a>无效</a>
                    </span>
                  </Popconfirm>

                  <Divider type="vertical" />
                </>
              ) : null}
              <span
                onClick={() => {
                  this.setState(
                    {
                      soldEdit: true,
                    },
                    () => {
                      this.props.dispatch({
                        type: 'order/view',
                        payload: record,
                      });
                    },
                  );
                }}
              >
                <a>修改</a>
              </span>
              {/* <Divider type="vertical" />
              <span
                onClick={() => {
                  this.props.dispatch({
                    type: 'buy/orderView',
                    payload: record,
                  });
                  this.setState({
                    visible: true,
                  });
                }}
              >
                <a>查看详情</a>
              </span> */}
            </>
          );
        },
      },
    ];

    return (
      <PageHeaderWrapper>
        <div
          className={styles.ordertype}
          style={{ padding: '6px 24px', background: '#fff', marginBottom: '6px' }}
        >
          <Radio.Group
            value={orderType}
            buttonStyle="solid"
            size="small"
            onChange={(e: any) => {
              this.props.dispatch({
                type: 'order/switchStatus',
                payload: e.target.value,
              });
            }}
          >
            <Radio.Button value="pendingOrder">未结算订单</Radio.Button>
            <Radio.Button value="settledOrder">结算订单</Radio.Button>
            <Radio.Button value="invalidOrder">无效订单</Radio.Button>
          </Radio.Group>
        </div>
        <div style={{ padding: '6px 24px', background: '#fff', marginBottom: '6px' }}>
          <Form layout="inline">
            <Form.Item label="方式：">
              {getFieldDecorator('type', {
                initialValue: '2',
              })(
                <Select>
                  <Option value="2">全部</Option>
                  <Option value="0">买入</Option>
                  <Option value="1">售出</Option>
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="购物人：">
              {getFieldDecorator('staffId', {
                initialValue: '',
              })(
                <Select
                  style={{ width: 220 }}
                  showSearch
                  // value={value}
                  placeholder="请输入工作人员"
                  // notFoundContent={fetching ? <Spin size="small" /> : null}
                  filterOption={false}
                  allowClear
                  onFocus={() => {
                    soldSearch({ comments: '' }).then(res => {
                      if (res.status == 200) {
                        this.setState({
                          personData: res.data,
                        });
                      } else {
                        this.setState({
                          personData: [],
                        });
                      }
                    });
                  }}
                  onSearch={value => {
                    soldSearch({ comments: value }).then(res => {
                      if (res.status == 200) {
                        this.setState({
                          personData: res.data,
                        });
                      } else {
                        this.setState({
                          personData: [],
                        });
                      }
                    });
                  }}
                  onChange={() => {}}
                >
                  {personData.length > 0
                    ? personData.map((item: any, index) => (
                        <Option key={item.id}>
                          {item.name}({item.phoneNumber})
                        </Option>
                      ))
                    : null}
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="时间：">
              {/* <Radio.Group
                value={selectDate}
                onChange={this.handlSelect}
                style={{ marginRight: '14px' }}
              >
                <Radio.Button value="day">日</Radio.Button>
                <Radio.Button value="month">月</Radio.Button>
                <Radio.Button value="period">时间段</Radio.Button>
              </Radio.Group> */}
              {/* {selectDate == 'day' ? (
                <DatePicker
                  size="default"
                  onChange={(val: any) => {
                    console.log(Number(moment(val).startOf('day')), 99999);
                    this.setState({
                      startTime: Number(moment(val).startOf('day')),
                      endTime: Number(moment(val).endOf('day')),
                    });
                  }}
                />
              ) : null}
              {selectDate == 'month' ? (
                <MonthPicker
                  placeholder="请选择月份"
                  format={'YYYY/MM'}
                  onChange={(date: any, dateString) => {
                    this.setState({
                      startTime: Number(moment(date).startOf('month')),
                      endTime: Number(moment(date).endOf('month')),
                    });
                  }}
                />
              ) : null}
              {selectDate == 'period' ? ( */}
              <RangePicker
                // defaultValue={[moment(0), moment()]}
                ranges={{
                  今日: [moment(), moment()],
                  当月: [moment().startOf('month'), moment().endOf('month')],
                }}
                showTime
                format="YYYY/MM/DD"
                onChange={([start, end]) => {
                  if (!start && !end) {
                    this.setState({
                      startTime: 0,
                      endTime: Date.now(),
                    });
                  } else {
                    this.setState({
                      startTime: Number(start),
                      endTime: Number(end),
                    });
                  }
                }}
              />
              {/* ) : null} */}
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                onClick={() => {
                  this.setState(
                    {
                      soldAdd: true,
                    },
                    () => {
                      this.props.dispatch({
                        type: 'order/view',
                        payload: {},
                      });
                    },
                  );
                }}
                style={{ marginRight: '14px' }}
              >
                新增
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  this.props.dispatch({
                    type: 'order/reFresh',
                    payload: true,
                  });
                }}
                style={{ marginRight: '14px' }}
              >
                搜索
              </Button>
              <Button type="primary" onClick={this.handleReset} style={{ marginRight: '14px' }}>
                重置
              </Button>
              <Button type="primary" icon="download" onClick={this.handleDown}>
                导出
              </Button>
            </Form.Item>
          </Form>
        </div>

        <Table
          bordered
          columns={columns}
          loading={isRefresh}
          scroll={{ x: 1500 }}
          dataSource={dataSource}
          size="middle"
          pagination={{
            pageSize: size,
            showSizeChanger: true,
            pageSizeOptions: ['5', '10', '20', '30'],
            current: page,
            total: total,
            onShowSizeChange: (current: any, size: any) => {
              this.setState(
                {
                  size: size,
                  page: 1,
                },
                () => {
                  this.handleSearch();
                },
              );
            },
            onChange: (page: any, pageSize: any) => {
              this.setState(
                {
                  page: page,
                },
                () => {
                  this.handleSearch();
                },
              );
            },
          }}
        />
        <Modal
          title="订单详情"
          visible={visible}
          maskClosable={true}
          footer={[
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                this.setState({
                  visible: false,
                });
              }}
            >
              关闭
            </Button>,
          ]}
          onCancel={() => {
            this.setState({
              visible: false,
            });
          }}
        >
          <Details />
        </Modal>

        <Modal
          title="新增"
          visible={soldAdd}
          forceRender
          destroyOnClose
          centered
          width={980}
          onOk={() => {
            this.soldAddRef.handleSubmit();
          }}
          onCancel={() => {
            this.setState({
              soldAdd: false,
            });
          }}
        >
          <Add
            close={() => {
              this.setState({
                soldAdd: false,
              });
            }}
            submit={(view: any, data: any) => {
              this.props.dispatch({
                type: 'order/add',
                payload: data,
              });
            }}
            wrappedComponentRef={(form: any) => (this.soldAddRef = form)} //5、使用wrappedComponentRef 拿到子组件传递过来的ref（官方写法）
          />
        </Modal>
        <Modal
          title="修改"
          visible={soldEdit}
          forceRender
          destroyOnClose
          centered
          width={980}
          onOk={() => {
            this.soldEditRef.handleSubmit();
          }}
          onCancel={() => {
            this.setState({
              soldEdit: false,
            });
          }}
        >
          <Edit
            close={() => {
              this.setState({
                soldEdit: false,
              });
            }}
            submit={(view: any, data: any) => {
              this.props.dispatch({
                type: 'order/edit',
                payload: { ...view, ...data },
              });
            }}
            wrappedComponentRef={(form: any) => (this.soldEditRef = form)} //5、使用wrappedComponentRef 拿到子组件传递过来的ref（官方写法）
          />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default connect(({ order }: any) => ({
  dataSource: order.list,
  total: order.total,
  isRefresh: order.isRefresh,
  orderType: order.orderType,
  // currentpage: order.number,
}))(Form.create()(Order));
